package com.movie.service.impl;

import com.movie.entity.Admin;
import com.movie.exception.ResourceNotFoundException;
import com.movie.mapper.AdminMapper;
import com.movie.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public Admin getAdminById(Long id) {
        Admin admin = adminMapper.findById(id);
        if (admin == null) {
            throw new ResourceNotFoundException("Admin not found with id: " + id);
        }
        return admin;
    }

    @Override
    public Admin getAdminByUsername(String username) {
        Admin admin = adminMapper.findByUsername(username);
        if (admin == null) {
            throw new ResourceNotFoundException("Admin not found with username: " + username);
        }
        return admin;
    }

    @Override
    public Admin login(String username, String password) {
        Admin admin = adminMapper.findByUsername(username);
        return admin;
    }

    @Override
    @Transactional
    public void updatePassword(Long id, String newPasswordHash) {
        int updatedRows = adminMapper.updatePassword(id, newPasswordHash);
        if (updatedRows == 0) {
            throw new RuntimeException("Failed to update password for admin id: " + id);
        }
    }
    
    @Override
    @Transactional
    public boolean updateAdmin(Admin admin) {
        try {
            adminMapper.updateAdmin(admin);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
} 